package com.yunpuvip.sachet.rest.common.util.pay;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alipay.api.*;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.parser.json.ObjectJsonParser;
import com.alipay.api.internal.parser.xml.ObjectXmlParser;
import com.alipay.api.internal.util.AlipayHashMap;
import com.alipay.api.internal.util.AlipayLogger;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import com.yunpuvip.sachet.biz.entity.Payment;
import com.yunpuvip.sachet.biz.service.SysparamService;
import com.yunpuvip.sachet.modular.constant.ApplicationConstant;
import com.yunpuvip.sachet.modular.core.exception.GunsException;
import com.yunpuvip.sachet.modular.core.exception.RestException;
import com.yunpuvip.sachet.modular.core.exception.RestServiceExceptionEnum;
import com.yunpuvip.sachet.modular.util.kit.HttpKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.IdGenerator;

import javax.servlet.http.HttpServletResponse;
import javax.sound.midi.SoundbankResource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ auther wushaohong
 * @ date  2019/8/24
 **/
@Component
@Slf4j
public class AliPayTool {

     @Autowired
     private SysparamService sysparamService;

    /**
     * 配置参数
     * @return
     * @throws AlipayApiException
     */
    public DefaultAlipayClient CerAlipay(AliPayBean aliPayBean) throws AlipayApiException {
        //构造client
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(aliPayBean.getServerUrl());
        certAlipayRequest.setAppId(aliPayBean.getAppId());
        certAlipayRequest.setPrivateKey(aliPayBean.getPrivateKey());
        //certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset("UTF-8");
        certAlipayRequest.setSignType("RSA2");
        certAlipayRequest.setCertPath(aliPayBean.getAppCertPath());
        certAlipayRequest.setAlipayPublicCertPath(aliPayBean.getAlipayCertPath());
        certAlipayRequest.setRootCertPath(aliPayBean.getRootCertPath());

        /*certAlipayRequest.setCertPath("C:\\Users\\fhfdfg\\Desktop\\CSR\\CSR\\appCertPublicKey.crt");
        certAlipayRequest.setAlipayPublicCertPath("C:\\Users\\fhfdfg\\Desktop\\CSR\\CSR\\alipayCertPublicKey_RSA2.crt");
        certAlipayRequest.setRootCertPath("C:\\Users\\fhfdfg\\Desktop\\CSR\\CSR\\alipayRootCert.crt");*/
        DefaultAlipayClient alipayClient = null;
        alipayClient = new DefaultAlipayClient(certAlipayRequest);
        return  alipayClient;
    }


    /**
     * 公钥证书支付
     * @param payment
     * @throws AlipayApiException
     */
    public String originPay(Payment payment) throws AlipayApiException {
        HttpServletResponse httpResponse = HttpKit.getResponse();
        //获取配置参数
        List<Map<String, Object>> alipayInfo = sysparamService.getAlipayInfo(ApplicationConstant.AlipaySysparam.PARAMCODE);
        if(alipayInfo.size()<7){
            throw new RestException(RestServiceExceptionEnum.ALIPAY_ERROR);
        }
        AliPayBean aliPayBean = getAliPayBean(alipayInfo);
        DefaultAlipayClient alipayClient = CerAlipay(aliPayBean);
        //获得初始化的AlipayClient
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();

        //创建API对应的request
        String returnUrl = aliPayBean.getReturnUrl();
        alipayRequest.setReturnUrl(returnUrl);
        //在公共参数中设置回跳和通知地址
        alipayRequest.setNotifyUrl(aliPayBean.getDomain()+aliPayBean.getNotifyUrl());
        System.out.println("回调地址："+aliPayBean.getDomain()+aliPayBean.getNotifyUrl());
        String payinfo = payment.getPayinfo();
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\"" +payment.getOrderNo()+"\"," +
                "    \"total_amount\":" +payment.getOrderPayPrice().toString()+"," +
                "    \"subject\":\"" +payment.getOrderNo()+"\"," +
                "    \"product_code\":\"QUICK_WAP_WAY\"" +
                "  }");

        //调用SDK生成表单
        try {
            System.err.println("业务参数："+alipayRequest.getBizContent());
            String body = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(body);
            return body;
        } catch (Exception e) {
            System.out.println("错误信息开始");
            e.getMessage();
            e.getCause();
            e.printStackTrace();
            System.out.println("错误信息结束");
        }
        return "支付信息有误";
    }


    /**
     * 获取参数
     * @param mapList
     * @param goal
     * @return
     */
    private String  getParam(List<Map<String,Object>> mapList,String goal) {
        for (Map<String, Object> ali : mapList) {
            String s = (String) ali.get("param_key");
            if (StrUtil.isNotEmpty(s)&&s.equals(goal)) {
                String paramValue = (String) ali.get("param_value");
                /*if(StrUtil.isEmpty(paramValue)){

                }*/
                return paramValue;
            }
        }
        return null;
    }

    /**
     * 支付公共参数封装
     * @param mapList
     * @return
     */

    public AliPayBean getAliPayBean(List<Map<String,Object>> mapList){
        AliPayBean aliPayBean = new AliPayBean();
        aliPayBean.setAppId(getParam(mapList,ApplicationConstant.AlipaySysparam.aliPayAppId));
        aliPayBean.setPrivateKey(getParam(mapList,ApplicationConstant.AlipaySysparam.privateKey));
        aliPayBean.setServerUrl(getParam(mapList,ApplicationConstant.AlipaySysparam.serverUrl));
        aliPayBean.setPublicKey(getParam(mapList,ApplicationConstant.AlipaySysparam.publicKey));
        aliPayBean.setNotifyUrl(getParam(mapList,ApplicationConstant.AlipaySysparam.aliPayNotify));
        aliPayBean.setDomain(getParam(mapList,ApplicationConstant.AlipaySysparam.domain));
        aliPayBean.setReturnUrl(getParam(mapList,ApplicationConstant.AlipaySysparam.aliPayReturnUrl));
        aliPayBean.setAlipayCertPath(getParam(mapList,ApplicationConstant.AlipaySysparam.AlipayCertPath));
        aliPayBean.setAppCertPath(getParam(mapList,ApplicationConstant.AlipaySysparam.AppCertPath));
        aliPayBean.setRootCertPath(getParam(mapList,ApplicationConstant.AlipaySysparam.RootCertPath));
        System.err.println("alipaybean:"+aliPayBean);
        return aliPayBean;
    }



}
